package com.yanqu.collectclientdata.db;

import com.alibaba.druid.util.JdbcUtils;
import com.yanqu.road.dao.db.DBPoolManager;
import com.yanqu.road.dao.db.DbParameter;
import com.yanqu.road.utils.ConfigHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * @Author wpj
 * @Date 2020/11/28
 */
public class CollectClientDbManager {
    private static final Logger logger = LogManager.getLogger(CollectClientDbManager.class.getName());

    private static DBPoolManager pools;

    public static boolean initDb() {
        pools = DBPoolManager.getInstance(ConfigHelper.getValue("db.path"));
        if (pools == null) {
            return false;
        }
//        Properties properties = new Properties();
//        String dbInfoValueHead = "jdbc:mysql://" + address + "/";
//        String dbInfoValueTail = "?useUnicode=true&characterEncoding=utf8&useSSL=false|" + userName + "|"
//                + password + "|" + connectNum;
//        properties.setProperty("CollectDb", dbInfoValueHead + dbName + dbInfoValueTail);
//        pools.addPools(properties);
        return true;
    }

    public static DBPoolManager getPools() {
        return pools;
    }

    /**
     * 获取连接
     * @return
     */
    public static Connection getConnection() {
        Connection myConn = null;
        try {
            myConn = pools.getConnection("db_collect");
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            JdbcUtils.close(myConn);
            myConn = null;
        }
        return myConn;
    }

    public static void closeConnection(PreparedStatement pstmt, ResultSet rs, Connection myConn) {
        JdbcUtils.close(rs);
        closeConnection(pstmt, myConn);
    }

    private static void closeConnection(PreparedStatement pstmt, Connection myConn) {
        try {

            if (pstmt != null && pstmt.isClosed() == false) {

                pstmt.clearParameters();
            }
            if (myConn.isClosed() == false) {

                if (myConn.getAutoCommit() != true) {
                    myConn.commit();
                    myConn.setAutoCommit(true);
                }
            }

        } catch (SQLException e) {
            logger.error(e.getMessage(), e);
        } finally {
            JdbcUtils.close(pstmt);
            JdbcUtils.close(myConn);
            myConn = null;
        }
    }

    public static int executeBatchQuery(String sqlText, List<Map<Integer, DbParameter>> params) {
        Connection myConn = getConnection();
        // DbWatch watch = new DbWatch();
        if (params == null || myConn == null)
            return -1;
        int count = 0;

        PreparedStatement pstmt = null;

        try {
            myConn.setAutoCommit(false);
            pstmt = myConn.prepareStatement(sqlText, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
            for (Map<Integer, DbParameter> map : params) {
                prepareCommand(pstmt, map);
                pstmt.addBatch();
                count++;
                if (count % 1500 == 0) {
                    pstmt.executeBatch();
                    myConn.commit();
                    count = 0;
                }
            }

            if (count > 0) {
                pstmt.executeBatch();
                myConn.commit();
            }

            return 1;
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        } finally {

            try {
                myConn.setAutoCommit(true);
            } catch (SQLException e) {
                logger.error(e.getMessage(), e);
            }
            closeConnection(pstmt, myConn);

            // watch.commit(sqlText);
        }
        return -1;
    }

    private static void prepareCommand(PreparedStatement pstmt, Map<Integer, DbParameter> parms) throws SQLException {
        if (parms == null)
            return;
        for (Map.Entry<Integer, DbParameter> entry : parms.entrySet()) {
            pstmt.setObject(entry.getKey(), entry.getValue().getResult());
        }
    }
}
